package address;

import helper.PinyinsHelper;
import jodd.bean.BeanCopy;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.weixin.WebUser;
import order.AdminOrder;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 社区
 * Created by buhaoba on 16/3/19.
 */
@Entity
@Table(name = "address_community")
public class Community extends BaseModel {

    /**
     * 所属配送区域
     */
    @JoinColumn(name = "city_id")
    @ManyToOne
    public City city;


    /**
     * 匹配微信号 用于发送模板消息
     */
    @JoinColumn(name = "web_user_id")
    @ManyToOne
    public WebUser webUser;

    /**
     * 小区名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 过滤小区名称
     */
    @Column(name = "search_name")
    public String searchName;

    /**
     * 拼音
     */
    @Column(name = "pinyin")
    public String pinyin;


    /**
     * 小区地址
     */
    public String address;


    /**
     * 负责人名称
     */
    @Column(name = "person")
    public String person;

    /**
     * 联系电话
     */
    @Column(name = "phone")
    public String phone;


    /**
     * 增加排序
     */
    @Column(name = "order_by")
    public Integer orderBy;

    /**
     * true:已加入
     * false:未加入
     */
    @Column(name = "isJoin")
    public Boolean isJoin = false;

    /**
     * 加入时间
     */
    @Column(name = "join_at")
    public Date joinAt;

    /**
     * 加入时间
     */
    @Transient
    public String joinAtStr;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    public Community() {
        super();
    }

    public Community(City city, String name, String address) {
        this.city = city;
        this.name = name;
        this.pinyin = PinyinsHelper.getFullSpell(name);
        this.address = address;
        this.deleted = DeletedStatus.UN_DELETED;
        this.createAt = new Date();
    }

    public Community(City city, WebUser webUser, String name, String address) {
        this.city = city;
        this.webUser = webUser;
        this.name = name;
        this.pinyin = PinyinsHelper.getFullSpell(name);
        this.address = address;
        this.deleted = DeletedStatus.UN_DELETED;
        this.createAt = new Date();
    }


    /**
     * 修改
     *
     * @param id
     * @param newObject
     */
    public static void update(Long id, Community newObject) {
        Community oldObject = Community.findById(id);
        newObject.pinyin = PinyinsHelper.getPingYin(newObject.name);
        BeanCopy.beans(newObject, oldObject).ignoreNulls(true).copy();
        oldObject.save();
    }

    public static Community findByPinYinOrName(String pinyin, String name) {
        if (pinyin.length() > 4) {
            return Community.find("(pinyin like ? or name like ? or substring(? , )) and deleted = ?", "%" + pinyin + "%", name + "%", DeletedStatus.UN_DELETED).first();
        } else {
            return Community.find("(pinyin = ? or name like ?) and deleted = ?", pinyin, name + "%", DeletedStatus.UN_DELETED).first();
        }
    }


    public static Community findByName(String name) {
        return Community.find("name = ? and deleted = ?", name, DeletedStatus.UN_DELETED).first();
    }

//    /**
//     * 分页查询.
//     */
//    public static JPAExtPaginator<Community> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
//        StringBuilder xsqlBuilder = new StringBuilder(" t.deleted=models.constants.DeletedStatus.UN_DELETED ")
//                .append("/~ and t.id = {id} ~/")
//                .append("/~ and t.name like {searchName} ~/")
//                .append("/~ and t.distributionAddress.name like {distributionAddressName} ~/")
//                .append("/~ and t.distributionAddress.id = {distributionAddressId} ~/");
//        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
//        JPAExtPaginator<Community> resultPage = new JPAExtPaginator<Community>("Community t", "t", Community.class,
//                result.getXsql(), conditionMap).orderBy(orderByExpress);
//        Logger.info("product Select SQL :" + result.getXsql() + "---");
//        resultPage.setPageNumber(pageNumber);
//        resultPage.setPageSize(pageSize);
//        resultPage.setBoundaryControlsEnabled(false);
//        return resultPage;
//    }

    /**
     * 查询配送区域下可用的小区
     *
     * @param distributionAddress
     * @return
     */
    public static List<Community> findAvailable(DistributionAddress distributionAddress) {
        return Community.find("deleted = ? and distributionAddress = ? order by orderBy desc", DeletedStatus.UN_DELETED, distributionAddress).fetch();
    }

    /**
     * 查询配送区域下可用的小区
     *
     * @param distributionAddressId
     * @return
     */
    public static List<Community> findAvailable(Long distributionAddressId) {
        return Community.find("deleted = ? and distributionAddress.id = ?", DeletedStatus.UN_DELETED, distributionAddressId).fetch();
    }

    /**
     * 根据ID查询
     */
    public static Community findByCommunityId(long id){
        return Community.find("id=? and deleted=?",id,DeletedStatus.UN_DELETED).first();
    }

    /**
     * 查询所有的小区
     *
     */
    public static List<Community> findAllCommunity(){
        return Community.find("deleted=?",DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 检查小区是否在地址管理业务里被使用
     */
    public static Boolean checkIsUsed(long id){
        boolean chenckAdminOrder= AdminOrder.count("tempCommunity.id=? and deleted=?",id,DeletedStatus.UN_DELETED)>0;
        boolean checkAddress=Address.count("community.id=?",id)>0;
       return (chenckAdminOrder && checkAddress)? true:false;
    }

    public static List<Community> findBySearchName(String name) {
        String _name = "%" + name + "%";
        return Community.find("deleted = ? and (name like ? or searchName like ?)" , DeletedStatus.UN_DELETED , _name , _name).fetch(10);
    }
}
